﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
using System.Threading.Tasks;
using VisionCloud.Domain.Filters;
using VisionSurface.Web.Authorize;

namespace VisionSurface.Web.Config
{
    /// <summary>
    /// jwt权限
    /// </summary>
    public static class JWTConfig
    {
        /// <summary>
        /// 初始化鉴权授权
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection InitJwtConfig(this IServiceCollection services)
        {
            //添加策略鉴权模式
            services.AddAuthorization(options =>
            {
                foreach (int v in Enum.GetValues(typeof(PolicyEnum)))
                {
                    string strName = Enum.GetName(typeof(PolicyEnum), v);
                    options.AddPolicy(strName, policy => policy.AddRequirements(new JwtTokenAuthorizationRequirement(strName)));
                }
            })
            .AddAuthentication(s =>
            {
                s.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                s.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                s.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            //添加jwt验证：
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime = true,//是否验证失效时间
                    ClockSkew = TimeSpan.Zero,
                    ValidateAudience = false,//是否验证Audience
                    ValidateIssuer = true,//是否验证Issuer
                    ValidIssuer = AuthCore.Domain,//Issuer，这两项和前面签发jwt的设置一致
                    ValidateIssuerSigningKey = true,//是否验证SecurityKey
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AuthCore.SecurityKey))//拿到SecurityKey
                };
                options.Events = new JwtBearerEvents
                {
                    OnAuthenticationFailed = context =>
                    {
                        return Task.CompletedTask;
                    }
                };
            });

            services.AddSingleton<JwtSecurityTokenHandler>();
            services.AddHttpContextAccessor();
            services.AddSingleton<IAuthorizationHandler, JwtTokenAuthorizationHandler>();
            services.AddHttpContextAccessor();

            return services;
        }
    }
}
